package news;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
	// UserDao:用户操作，包括public NewsUser login(String u, String p),add(NewsUser u)

	public NewsUser login(String u, String p) {
		Connection conn = DBUtil.getConnection();
		String sql = "SELECT * FROM news_users WHERE uname=? AND upwd=?;";
		NewsUser user = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, u);
			ps.setString(2, p);
			rs = ps.executeQuery();
			if (rs.next()) {
				user = new NewsUser();
				user.setUid(rs.getInt("uid"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("upwd"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, conn);
		}
		return user;
	}

	public int add(NewsUser u) {
		String sql = "INSERT INTO  news_users(uname,upwd) VALUES(?,?);";
		return DBUtil.executeUpdate(sql, u.getUname(), u.getUpwd());
	}
}